package net.jxtz.jxtzos.util;

import org.apache.http.HttpEntity;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author a123
 */
public final class ResponseUtil {

    public static String entityToString(HttpEntity entity){
        String result = null;
        if (entity != null) {
            long lenth = entity.getContentLength();
            if (lenth != -1 && lenth < 2048) {
                try {
                    result = EntityUtils.toString(entity, "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                InputStreamReader reader1 = null;
                try {
                    reader1 = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l = 0;
                while (true) {
                    try {
                        if (!((l = reader1.read(tmp)) != -1)) break;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }

}
